#!/usr/bin/env python3
"""
后端连接检查脚本
用于验证后端API是否正常运行
"""

import requests
import json
from urllib.parse import urljoin

# 配置
BACKEND_URL = "http://localhost:8000"

def check_health():
    """检查健康状态"""
    try:
        response = requests.get(f"{BACKEND_URL}/health", timeout=5)
        if response.status_code == 200:
            data = response.json()
            print(f"✅ 健康检查通过: {data}")
            return True
        else:
            print(f"❌ 健康检查失败: HTTP {response.status_code}")
            return False
    except requests.exceptions.RequestException as e:
        print(f"❌ 无法连接到后端: {e}")
        return False

def check_documents_api():
    """检查文档API"""
    try:
        response = requests.get(f"{BACKEND_URL}/api/documents/", timeout=5)
        if response.status_code == 200:
            docs = response.json()
            print(f"✅ 文档列表API正常: 共 {len(docs)} 个文档")
            return True
        else:
            print(f"❌ 文档列表API失败: HTTP {response.status_code}")
            return False
    except requests.exceptions.RequestException as e:
        print(f"❌ 文档API连接失败: {e}")
        return False

def check_cors():
    """检查CORS配置"""
    try:
        response = requests.options(
            f"{BACKEND_URL}/api/documents/",
            headers={
                'Origin': 'http://localhost:8080',
                'Access-Control-Request-Method': 'GET',
            },
            timeout=5
        )
        cors_header = response.headers.get('Access-Control-Allow-Origin')
        if cors_header:
            print(f"✅ CORS配置正常: {cors_header}")
            return True
        else:
            print("⚠️  警告: 未检测到CORS头，可能会有跨域问题")
            return False
    except requests.exceptions.RequestException as e:
        print(f"❌ CORS检查失败: {e}")
        return False

def main():
    """主函数"""
    print("=" * 60)
    print("RAG 智能问答系统 - 后端连接检查")
    print("=" * 60)
    print(f"检查目标: {BACKEND_URL}")
    print("=" * 60)
    print()
    
    # 执行检查
    results = []
    
    print("1. 检查后端健康状态...")
    results.append(check_health())
    print()
    
    print("2. 检查文档API...")
    results.append(check_documents_api())
    print()
    
    print("3. 检查CORS配置...")
    results.append(check_cors())
    print()
    
    # 总结
    print("=" * 60)
    if all(results[:2]):  # 前两项必须通过
        print("✅ 后端连接正常！可以启动前端服务了。")
        print()
        print("下一步:")
        print("1. 运行 start.bat (Windows) 或 ./start.sh (Linux/Mac)")
        print("2. 或运行 python start_server.py")
        print("3. 在浏览器访问 http://localhost:8080")
    else:
        print("❌ 后端连接异常！请先启动后端服务。")
        print()
        print("启动后端的方法:")
        print("cd ..")
        print("python -m uvicorn app.main:app --reload")
    print("=" * 60)

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n操作已取消")

